package dk.muldbjergskolen.db;

import dk.muldbjergskolen.model.*;

import java.sql.*;
import java.util.ArrayList;

public class TidsIntervalDB {

	private Connection con;

	public TidsIntervalDB() {
		con = ConnectionDB.getInstance().getDBcon();
	}

	public ArrayList<TidsInterval> getTidsInterval() {
		ArrayList<TidsInterval> tidsinterval = new ArrayList<TidsInterval>();
		TidsInterval tI = null;
		String query = "Select * from TidsInterval";

		try {
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			ResultSet rs = stmt.executeQuery(query);

			while (rs.next()) {
				tI = buildTidsInterval(rs);
				tidsinterval.add(tI);
			}
			rs.close();
		} catch (SQLException e) {
			// e.printStackTrace();
		}
		return tidsinterval;
	}

	public TidsInterval getTidsInterval(int tidsIntervalId) {
		TidsInterval tidsInterval = null;
		String query = "SELECT id, starttid, sluttid FROM TidsInterval WHERE id = "
				+ tidsIntervalId + "";

		try {
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			ResultSet rs = stmt.executeQuery(query);

			if (rs.next()) {
				tidsInterval = buildTidsInterval(rs);
			}
			rs.close();
		} catch (SQLException e) {
			// e.printStackTrace();
		}

		return tidsInterval;
	}

	public TidsInterval buildTidsInterval(ResultSet result) {
		TidsInterval tI = null;

		try {
			tI = new TidsInterval(result.getInt("id"),
					result.getTime("starttid"), result.getTime("sluttid"));
		}

		catch (Exception e) {
			System.out.println("Fejl i opbygningen af Tidsintervaller.");
		}

		return tI;
	}

}
